use "$datapath/A3_age55data_WC_rdrobust.dta",clear


{ // Indicate first observations of new job
*===============================================================================
*Condtion on newfirm==1 and observred wage (post eventtime>=0 by construction)
bys lopnr (eventtime_def) : gen nvals = sum(newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid) if newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid
gen xnvalsdate = date if nvals==1 
bys lopnr (eventtime_def) : egen nvalsdate = max(xnvalsdate) // impute for all obs this value
format nvalsdate %tm

/*
*Generte same as above but correct for observing the wage possibly earlier
bys lopnr (eventtime) : gen nvals2 = sum(1) if firmid_lonestruktur==firstnewfirmid & eventtime_def>=0 & firmid_lonestruktur!=.
gen xnvals2date = date if nvals2==1 
bys lopnr (eventtime_def) : egen nvals2date = max(xnvals2date) // impute for all obs this value
format nvals2date %tm

*Indicate first wage from new firm in wage survey (no matter the firm and RAMS indicators)
bys lopnr (eventtime) : gen nvals4 = sum(1) if firmid!=firmid_lonestruktur & firmid_lonestruktur!=. & eventtime_def>=0
*/


*Pre wage from notifying firm (last observred wage at notifying firm before or at notification)
bys lopnr (eventtime_def) : gen nvals3 = _n if manl!=. & date<=nvalsdate & eventtime_def<=0
bys lopnr (eventtime_def) : egen maxnvals3 = max(nvals3)


*Date for last wage at notifying firm (within 2 yers before notification)
gen xnvals3date = date if nvals3==maxnvals3	& nvals3!=. & inrange(eventtime_def,-24,0)
bys lopnr (eventtime_def) : egen nvals3date = max(xnvals3date)
format nvals3date %tm

*Difference in time between old and new wage
gen diff = nvalsdate - nvals3date
sum diff if nvals==1

*Wage at notifying firm	
gen xprewage = manl if date==nvals3date 
bys lopnr (eventtime_def) : egen prenotfwage = max(xprewage)
drop xprewage

*fixa sa att datumet for gamla lonen inte far vara efter nya jobbet fas (i.e date of nvals3 < date of nvals)

*Generate eventtime for wage growth (i.e time after having found new job)
bys lopnr (eventtime_def) : gen timeafterjob = sum(1) if nvals>=1 & date>= nvalsdate


}
*

{ // Generate wages
*===============================================================================
*Generate log wage variables 
gen log_manl_newfirm = log(manl_newfirm)
bys lopnr (eventtime_def) : gen preobswage= manl_firstnewfirmid[_n-12]!=. & nvals==1 & eventtime_def[_n-12]>=0
bys lopnr (eventtime_def) : replace log_manl_newfirm = log(manl_firstnewfirmid[_n-12]) if preobswage==1
gen diff_log_manl_newfirm = log(manl_newfirm) - log(prenotfwage)
gen log_prenotfwage = log(prenotfwage)

*Generate wage growth per year
gen firstnewwage = manl_newfirm if nvals==1
bys lopnr (eventtime_def) : egen fill_manl_newfirm = max(firstnewwage) 
bys lopnr (eventtime_def) : gen wgrowth = log(manl_newfirm) - log(fill_manl_newfirm)


}
*
*
{ // Generate: Event time to displacement
*===============================================================================
bys lopnr (date) : gen lastmonthwork =  date if  atfirm2[_n-1]==1 & atfirm2==1 & atfirm2[_n+1]==0  & atfirm2[_n+2]==0 
format lastmonthwork %tm

bys lopnr (date) : gen SPnvals = sum(1) 	if lastmonthwork!=.
tab SPnvals 				if lastmonthwork!=.
bys lopnr : egen maxnvals = max(SPnvals)

*Take away displacemnt dates that occur 12 months before notification for those with multiple displacments dates
replace lastmonthwork=. if eventtime_def<-12 & maxnvals>1


bys lopnr (date) : gen SPnvals2 = sum(1) 	if lastmonthwork!=.
tab SPnvals2 				if lastmonthwork!=.
bys lopnr : egen maxnvals2 = max(SPnvals2)
*Now 93.87 percent are displaced only once

 gen SPdiff = lastmonthwork - notdate_def
 tab SPdiff treat 
*So very few do not work 12 months prior to notification so we get rid of these
replace lastmonthwork=. if eventtime_def<-12
drop SPdiff

   
*Taking the minimum date assures that we get the nvals==1 as displacement date
fastmin lastmonthwork , by(lopnr) name(dispdate)
replace dispdate = dispdate +1
format dispdate %tm

*Recalls (working 3 months after displacement event has occured)
bys lopnr (date) : gen xrecalldate = date if atfirm2[_n-2]==0 & atfirm2[_n-1]==0 & atfirm2==1 & atfirm2[_n+1]==1 & atfirm2[_n+3]==1 & date>dispdate
fastmin xrecalldate , by(lopnr) name(recalldate)
format recalldate %tm
drop x*
gen recalled = recalldate!=.   
   
*Generate: Month of displacement
gen monthofdisp = month(dofm(dispdate))

*Generate: Months worked after notification
gen RAMSmonths = dispdate - notdate_def

*Generate: Displacement event time
bys lopnr (date) : gen dispeventtime = date - dispdate

drop SPnvals*
}
*

merge m:1 lopnr year using "$datapath/SP.dta"
drop if _merge==2
drop _merge


{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "	
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*

xtset ym_def

gen xlognewwage = log_manl_newfirm if nvals==1 & eventtime_def<=24  
bys lopnr: egen lognewwage = max(xlognewwage)

gen xdifflognewwage = diff_log_manl_newfirm if nvals==1 & eventtime_def<=24   
bys lopnr: egen difflognewwage = max(xdifflognewwage)

gen xSP5 = SP5_win_1_99/1000 if SP5_win_1_99!=. & dispeventtime==0 
bys lopnr: egen maxSP5 = max(xSP5)

gen xannual_tp1 = annual_ear/1000 if eventtime_def==12
bys lopnr : egen annual_tp1 = max(xannual_tp1)

gen nonemp 	= working2==0 
bys lopnr (date) : egen xcumnonemployed 	= total(atfirm2==0 & working2==0) 	if inrange(eventtime_def,1,24) 
bys lopnr : egen cumnonemployed = max(xcumnonemployed)



keep if eventtime_def==0
replace nottime_def=nottime_def/30
gen runvar2 = round(runvar*12)

foreach outvar of varlist  nottime_def annual_tp1 cumnonemployed maxSP5  lognewwage difflognewwage {	
	eststo clear
		
		*Original estimate
		eststo: qui xtreg `outvar'			$instrument $linear $covariets if inrange(runvar,-3,3)  , cluster(varselid) fe nonest 
		estadd scalar band = 3
		estadd scalar poly = 1
		*Linear
		eststo: qui xtreg `outvar'			$instrument $linear $covariets if inrange(runvar,-1,1)  , cluster(varselid) fe nonest 
		estadd scalar band = 1
		estadd scalar poly = 1
		eststo: qui xtreg `outvar'			$instrument $linear $covariets if inrange(runvar,-2,2)  , cluster(varselid) fe nonest 
		estadd scalar band = 2
		estadd scalar poly = 1
		eststo: qui xtreg `outvar'			$instrument $linear $covariets if inrange(runvar,-4,4)  , cluster(varselid) fe nonest
		estadd scalar band = 4
		estadd scalar poly = 1
		
		*Donut estimate
		eststo: qui xtreg `outvar'			$instrument $linear $covariets if inrange(runvar,-3,3) & !inrange(runvar2,-3,3) , cluster(varselid) fe nonest 
		estadd scalar band = 3
		estadd scalar poly = 1

		rdbwselect `outvar' runvar  , vce(cluster varselid) masspoints(none) c(0) all covs($covariets )
		local b = e(h_mserd)
		eststo: qui xtreg `outvar'			$instrument $linear $covariets if inrange(runvar,-`b',`b')  , cluster(varselid) fe nonest
		estadd scalar band = `b' 
		estadd scalar poly = 1

		eststo:  rdrobust `outvar' runvar, vce(cluster varselid) c(0) masspoints(none) all covs($covariets )
		estadd scalar band = e(h_l)
		estadd scalar poly = 1



		*Quadratic
		eststo: qui xtreg `outvar'			$instrument $quadratic $covariets if inrange(runvar,-1,1)  , cluster(varselid) fe nonest 
		estadd scalar band = 2
		estadd scalar poly = 2
		eststo: qui xtreg `outvar'			$instrument $quadratic $covariets if inrange(runvar,-2,2)  , cluster(varselid) fe nonest 
		estadd scalar band = 3
		estadd scalar poly = 2
		eststo: qui xtreg `outvar'			$instrument $quadratic $covariets if inrange(runvar,-4,4)  , cluster(varselid) fe nonest
		estadd scalar band = 4
		estadd scalar poly = 2

		*Donut estimate
		eststo: qui xtreg `outvar'			$instrument $quadratic $covariets if inrange(runvar,-3,3) & !inrange(runvar2,-3,3) , cluster(varselid) fe nonest 
		estadd scalar band = 3
		estadd scalar poly = 1
		
		rdbwselect `outvar' runvar  , vce(cluster varselid) masspoints(none) c(0) all p(2) covs($covariets )
		local b = e(h_mserd)
		eststo: qui xtreg `outvar'			$instrument $quadratic $covariets if inrange(runvar,-`b',`b')  , cluster(varselid) fe nonest
		estadd scalar band = `b' 
		estadd scalar poly = 2

		eststo:  rdrobust `outvar' runvar, vce(cluster varselid) c(0) masspoints(none) all p(2) covs($covariets )
		estadd scalar band = e(h_l)
		estadd scalar poly = 2
		esttab , keep($instrument  Bias-corrected) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) ///
		stats( band poly N, fmt( %9.2fc %9.0fc %9.0fc) )

	
	
	if "`outvar'"=="nottime_def" {
		local outlabel "Notification time (days)"
	}
	if "`outvar'"=="annual_tp1" {
		local outlabel "Annual earnings $ t+1 $ (1000 SEK)"
	}
	if "`outvar'"=="cumnonemployed" {
		local outlabel "Months non-employed within 2 years"
	}
	if "`outvar'"=="maxSP5" {
		local outlabel "Severance pay (1000 SEK)"
	}
	if "`outvar'"=="lognewwage" {
		local outlabel "log(wage)"
	}
	if "`outvar'"=="difflognewwage" {
		local outlabel " $ \Delta $ log(wage)"
	}
	

	if "`outvar'"=="nottime_def" {
		esttab using "$agetablepath/Robust/Robust_alloutcomes_inD.tex", 				/// 
		replace keep($instrument Bias-corrected ) booktabs nodepvars  nomtitles nolines	nonumbers		///
		varlabels(treat "`outlabel'" _cons "Control mean" above55EE "Above age-55 $ \times $ EE" EtoE "EE" ) se(2) b(2)  			///
		star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
		stats(band poly N, fmt( %9.2fc %9.0fc %9.0fc)  /// 
		labels( "\quad Bandwidth " " \quad Polynomial degree" " \quad \# observations")) ///
		nonotes ///
		prehead("\begin{table}[htbp]\centering \scriptsize" ///
		"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" ///
		"\caption{Sensitivity of RD-design to bandwidth and functional form}" ///
		"\begin{tabular}{l*{13}{c}}" ///
		"\midrule" ///
		"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8)&(9)&(10)&(11)&(12)&(13) \\" ///
		"\midrule" ) end(" \\") begin("") postfoot("")
		
	}
	else if "`outvar'"=="difflognewwage" {
		esttab using "$agetablepath/Robust/Robust_alloutcomes_inD.tex", 				/// 
		append keep($instrument Bias-corrected ) booktabs nodepvars  nomtitles nolines	nonumbers		///
		varlabels(treat "`outlabel'" _cons "Control mean" above55EE "Above age-55 $ \times $ EE" EtoE "EE" ) se(3) b(3)  			///
		star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _) ///
		stats(band poly N, fmt( %9.2fc %9.0fc %9.0fc)  /// 
		labels( "\quad Bandwidth " " \quad Polynomial degree" " \quad \# observations")) ///
		nonotes ///
		prehead("\addlinespace" ) end("\\ ") begin("") ///
		postfoot("\bottomrule \end{tabular} \end{table}") 
	}
	else  {
		esttab using "$agetablepath/Robust/Robust_alloutcomes_inD.tex", 				/// 
		append keep($instrument Bias-corrected ) booktabs nodepvars  nomtitles nolines	nonumbers		///
		varlabels(treat "`outlabel'" _cons "Control mean" above55EE "Above age-55 $ \times $ EE" EtoE "EE" ) se(3) b(3)  			///
		star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
		stats(band poly N, fmt( %9.2fc %9.0fc %9.0fc)  /// 
		labels( "\quad Bandwidth " " \quad Polynomial degree" " \quad \# observations")) ///
		nonotes ///
		 end(" \\") begin("") postfoot("") prehead("\addlinespace" )
		
	}
	
	
}
